package com.sxy.web.request;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author 宋鑫宇
 * @version 1.0
 * Request 请求方式的一些方法使用
 */
@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String getMethod() : 获取请求方式
        String method = req.getMethod();
        System.out.println(method);
        //获取虚拟目录（项目访问路径）
        String contextPath = req.getContextPath();
        System.out.println(contextPath);
        //获取URL(统一资源定位符)
        StringBuffer requestURL = req.getRequestURL();
        System.out.println(requestURL.toString());
        //获取URI(统一资源标识符)：
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);
        //获取请求参数
        String queryString = req.getQueryString();
        System.out.println(queryString);
        /*
            获取请求头的方式
            String header = req.getHeader(String name);//根据请求头名称来获取值
         */
        //获取请求头,user-agent：浏览器版本信息
        String header = req.getHeader("user-agent");
        System.out.println(header);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
            post方法传输，获取请求体的数据
            ServletInputStream getInputStream() : 获取字节输入流
            BufferReader getReader() : 获取字符输入流
         */
        //获取字节输入流
//        ServletInputStream inputStream = req.getInputStream();
//        byte[] read = new byte[1024];
//        System.out.println(new String(read));
        //获取字符输入流
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        System.out.println(s);
    }
}
